package com.liveinstars.common.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * This program generates a AES key, retrieves its raw bytes, and then
 * reinstantiates a AES key from the key bytes. The reinstantiated key is used
 * to initialize a AES cipher for encryption and decryption.
 */

public class AESUtil {

    private static final String AES = "AES/CBC/PKCS5Padding";

    private static final String CRYPT_KEY = "WTAHAPPYACTIVITY";

    /**
     * 加密
     */
    public static byte[] encrypt(byte[] src, String key) throws Exception {
        Cipher cipher = Cipher.getInstance(AES);
        SecretKeySpec securekey = new SecretKeySpec(key.getBytes(), "AES");
        // 初始化向量,在密钥相同的前提下，加上初始化向量，相同内容加密后相同
        IvParameterSpec zeroIv = new IvParameterSpec(key.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, securekey, zeroIv);//设置密钥和加密形式
        return cipher.doFinal(src);
    }

    /**
     * 解密
     */
    public static byte[] decrypt(byte[] src, String key) throws Exception {
        Cipher cipher = Cipher.getInstance(AES);
        SecretKeySpec securekey = new SecretKeySpec(key.getBytes(), "AES");//设置加密Key
        // 初始化向量,在密钥相同的前提下，加上初始化向量，相同内容加密后相同
        IvParameterSpec zeroIv = new IvParameterSpec(key.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, securekey, zeroIv);//设置密钥和解密形式
        return cipher.doFinal(src);
    }

    /**
     * 二行制转十六进制字符串
     */
    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs = hs + "0" + stmp;
            else
                hs = hs + stmp;
        }
        return hs.toUpperCase();
    }

    public static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0)
            throw new IllegalArgumentException("长度不是偶数");
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        return b2;
    }

    /**
     * 解密
     */
    public final static byte[] decrypt(String data) throws Exception {
        return decrypt(data, CRYPT_KEY);
    }

    /**
     * 加密
     */
    public final static byte[] encrypt(String data) throws Exception {
        return encrypt(data, CRYPT_KEY);
    }

    /**
     * 解密
     */
    public final static byte[] decrypt(String data, String cryptKey) throws Exception {
        try {
            return decrypt(data.getBytes(), cryptKey);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 加密
     */
    public final static byte[] encrypt(String data, String cryptKey) throws Exception {
        try {
            return encrypt(data.getBytes(), cryptKey);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 解密
     */
    public final static String decryptWithHex(String data) throws Exception {
        return decryptWithHex(data, CRYPT_KEY);
    }

    /**
     * 加密
     */
    public final static String encryptWithHex(String data) throws Exception {
        return encryptWithHex(data, CRYPT_KEY);
    }

    /**
     * 解密
     */
    public final static String decryptWithHex(String data, String cryptKey) throws Exception {
        try {
            return new String(decrypt(hex2byte(data.getBytes()),
                    cryptKey));
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 加密
     */
    public final static String encryptWithHex(String data, String cryptKey) throws Exception {
        try {
            return byte2hex(encrypt(data.getBytes(), cryptKey));
        } catch (Exception e) {
            throw e;
        }
    }


    public static void main(String[] args) throws Exception {
        String context = "HELLOWORLD";
        String key = "1234567812345678";
        byte[] aes = encrypt(context.getBytes(), key);
        String base64 = Base64.getEncoder().encodeToString(aes);
        System.out.println("base64 " + base64);

        byte[] deBase64 = Base64.getDecoder().decode(base64);
        String old = new String(decrypt(deBase64, key));
        System.out.println("old " + old);


    }

}